﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：吕海乐 
    //
    // 文件名：PurchaseOrderDetailAdd.cs
    // 文件功能描述：新建采购单，加入采购单明细
    // 创建标识：吕海乐2009-05-12
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using System.Collections.Generic;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Hospitals.Procurement
{
    public partial class PurchaseOrderDetailAdd : BasePage
    {
        public PurchaseOrderDetailAdd()
        {
            this.ModuleNo = Module.采购单管理.ToString();
        }

        IBLL_Distribution id = Factory.BLL_Distribution();
        IBLL_Purchase ip = Factory.BLL_Purchase();
        IBLL_ProcurementBasic ipb = Factory.BLL_ProcurementBasic();
        IBLL_HospitalProcureCatalog hpcCtrl = Factory.BLL_HospitalProcureCatalog();

        IBLL_Company ic = Factory.BLL_Company();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HZ.DrugTrade.Web.Function.IsThreeLevel())//项目查询条件仅三级医院可见
            {
                this.ddlProjectid.Visible = false;
                this.lblProjectid.Visible = false;
            }
            if (!IsPostBack)
            {
                //绑定该医疗机构所有可选的采购目录
                BindCatalog();
            }
        }

        /// <summary>
        /// 绑定该医疗机构所有可选的采购目录(采购目录启用，医疗机构启用了该采购目录,医疗机构未选择的)
        /// </summary>
        private void BindCatalog()
        {
            int totalCount = 0;
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;

            //绑定所有符合条件的目录（采购目录启用，医疗机构启用了该采购目录）
            Model.Query.HospitalProcureCatalog hospitalProcureCatalog = GetCondition();

            IList<Model.View.HospitalProcureCatalog> hosiptalCatalogList = hpcCtrl.GetHospitalProcureCatalog(hospitalProcureCatalog, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            AspNetPager1.RecordCount = totalCount;
            gvwProduceCatalog.DataSource = hosiptalCatalogList;
            gvwProduceCatalog.DataBind();

            if (totalCount > 0)
            {
                gvwProduceCatalog_Check();
            }
        }
        /// <summary>
        /// 检验该产品是否可采购
        /// </summary>
        protected void gvwProduceCatalog_Check()
        {
            int rowCount = gvwProduceCatalog.Rows.Count;
            //暂时用SNKEY标识是否缴费 
            IList<Model.Company> lst = ic.GetCompanyByWhere(" where CompanyType<>2 and SNKEY=2");
            if (lst != null && lst.Count > 0)
            {
                foreach (Model.Company item in lst)
                {
                    for (int i = 0; i < rowCount; i++)
                    {
                        if (item.CompanyID.ToUpper() == gvwProduceCatalog.DataKeys[i]["CompanyID_TB"].ToString().ToUpper())
                        {
                            //gvwProduceCatalog.Rows[i].Attributes.Add("style", "backgroundColor:#fff;");
                            ((TextBox)gvwProduceCatalog.Rows[i].FindControl("txtCount")).Enabled = false;
                            ((CheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1")).Enabled = false;

                            //foreach (var item in gvwProduceCatalog.Rows[i].Cells)
                            //{
                            //    //
                            //}
                            for (int _intCount = 0; _intCount < gvwProduceCatalog.Rows[i].Cells.Count; _intCount++)
                            {
                                gvwProduceCatalog.Rows[i].Cells[_intCount].Attributes.Clear();
                                gvwProduceCatalog.Rows[i].Cells[_intCount].Attributes.Add("bgcolor", "red");
                            }
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            BindCatalog();
        }

        /// <summary>
        /// 将所选产品加入采购单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            List<PurchaseOrderDetail> detailList = new List<PurchaseOrderDetail>();
            for (int i = 0; i < gvwProduceCatalog.Rows.Count; i++)
            {
                CheckBox chk = (CheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1");
                TextBox txtPurchaseCount = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtCount");
                // Label lblPrcie = (Label)gvwProduceCatalog.Rows[i].FindControl("lblPrice");
                Label lblPrice = (Label)gvwProduceCatalog.Rows[i].FindControl("lblPrice");
                if (chk.Checked == true)
                {
                    //采购数量不能为空
                    if (string.IsNullOrEmpty(txtPurchaseCount.Text.Trim()))
                    {
                        HZ.Web.WebUtil.Alert("采购数量不能为空！", this);
                        txtPurchaseCount.Focus();
                        return;
                    }

                    //输入的采购数量为非法字符
                    if ((new HZ.Common.ConvertHelper(txtPurchaseCount.Text.Trim()).ToInt32) == null)
                    {
                        HZ.Web.WebUtil.Alert("输入的采购数量为非法字符！", this);
                        txtPurchaseCount.Focus();
                        return;
                    }

                    //采购数量不能为“0”
                    if ((new HZ.Common.ConvertHelper(txtPurchaseCount.Text.Trim()).ToInt32) == 0)
                    {
                        HZ.Web.WebUtil.Alert("采购数量不能为0！", this);
                        txtPurchaseCount.Focus();
                        return;
                    }

                    //将所选目录放入列表
                    PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();
                    purchaseOrderDetail.OrderID = Request.QueryString["orderID"];
                    purchaseOrderDetail.Price = new HZ.Common.ConvertHelper(lblPrice.Text.Trim()).ToDecimal;
                    purchaseOrderDetail.ProcureCatalogID = gvwProduceCatalog.DataKeys[i].Values[0].ToString();
                    purchaseOrderDetail.PurchaseCount = new HZ.Common.ConvertHelper(txtPurchaseCount.Text.Trim()).ToInt32;
                    purchaseOrderDetail.Amount = purchaseOrderDetail.Price * purchaseOrderDetail.PurchaseCount;
                    purchaseOrderDetail.CompanyID_PS = gvwProduceCatalog.DataKeys[i].Values[1].ToString();
                    purchaseOrderDetail.FlowID = "1";
                    detailList.Add(purchaseOrderDetail);
                }
            }

            int flag = ip.AddPurchaseOrderDetail_Batch(detailList);
            if (flag == 1)
            {
                HZ.Web.WebUtil.Alert("产品已添加到采购单，可继续添加，结束请单击“制单完成”", this);
                BindCatalog();
            }
            else if (flag == 2)
            {
                PageError("采购单中已经存在要添加的产品，请重试！", "");
            }
            else
            {
                PageError("添加失败，请联系管理员！", "");
            }
        }

        /// <summary>
        /// 完成采购单的制作，转至采购单维护列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFinish_Click(object sender, EventArgs e)
        {
            btnAdd_Click(null, null);
            HZ.Web.WebUtil.RedirectByScript("PurchaseOrderUpdate.aspx?OrderID=" + Request.QueryString["orderID"]);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            BindCatalog();
        }


        /// <summary>
        /// 获取查询条件
        /// </summary>
        /// <returns></returns>
        private Model.Query.HospitalProcureCatalog GetCondition()
        {
            Model.Query.HospitalProcureCatalog hospitalProcureCatalog = new HZ.DrugTrade.Model.Query.HospitalProcureCatalog();
            hospitalProcureCatalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            hospitalProcureCatalog.Companyname_Sc = txtProduceCompany_SC.Text.Trim();
            //hospitalProcureCatalog.PinyinCode = this.txtPinyinCode.Text.Trim().ToUpper();
            hospitalProcureCatalog.Outlookc = txtOutLook.Text.Trim();
            //hospitalProcureCatalog.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                hospitalProcureCatalog.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                hospitalProcureCatalog.ProjectID = "0001";
            }
            hospitalProcureCatalog.GoodsName = txtGoodsName.Text.Trim();
            hospitalProcureCatalog.PinyinCode = this.txtpinyincode.Text.Trim();
            hospitalProcureCatalog.Unit = txtUnit.Text.Trim();
            hospitalProcureCatalog.PackUnit = txtPackUnit.Text.Trim();
            //string orgID = CurrentAccount.GetUser().Org.OrgID;
            //bool flag = ipb.GetIsJiCeng(orgID);//判断是否基层医疗机构 add by zdc
            //if (flag)//盟市添加的只能采购基本药物和内蒙基本药物 zdc
            //{
            //    hospitalProcureCatalog.IsJiCeng = 0;
            //}
            hospitalProcureCatalog.Companyname_Ps = txtCompany_PS.Text.Trim();
            hospitalProcureCatalog.Companyname_Tb = txtCompany_TB.Text.Trim();
            hospitalProcureCatalog.SortFields = " GoodsName asc ,Outlookc asc,goodsid";
            //if (ucIsBasicRemedy1.SelectValue != -1) hospitalProcureCatalog.IsBasicRemedy = ucIsBasicRemedy1.SelectValue;
            hospitalProcureCatalog.IsUsing = true;
            hospitalProcureCatalog.Hospital_IsUsing = true;

            //获取采购单中以后的采购目录编号
            string strAppendSql = "select procurecatalogid from  tb_PurchaseOrderDetail  where orderid ='" + Request.QueryString["orderID"] + "'";
            hospitalProcureCatalog.Append = "ProcureCatalogID Not in (" + strAppendSql + ")";

            return hospitalProcureCatalog;
        }

        /// <summary>
        /// 简单查询与高级查询间的转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据

                txtCompany_TB.Text = "";
                txtPackUnit.Text = "";
                //txtPinyinCode.Text = "";

                txtProduceCompany_SC.Text = "";
                txtCompany_PS.Text = "";
                txtCompany_TB.Text = "";
                txtUnit.Text = "";

            }
        }

        protected void gvwProduceCatalog_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (ddlProjectid.SelectedItem.Value == "0002")
                {
                    e.Row.Cells[3].Text = "自主报价";
                }
                else
                {
                    e.Row.Cells[3].Text = "采购限价";
                }
            }
        }
    }
}
